<template>
  <div ref="oScrollWrap" class="scroll-wrap" :style="{ width, height }">
    <div class="scroll-inner">
      <slot></slot>
      <div ref="observerElement" class="load-more">加载更多...</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
 
const props = defineProps({
  width: { type: String, default: '100vw' },
  height: { type: String, default: '100vh' },
  finshed: { type: Boolean, default: false },
})

const emit = defineEmits(['more'])
function callback(entries) {
  entries.forEach((entry) => {
    if (entry.isIntersecting && !props.finshed) {
      emit('more')
    }
  })
}

const oScrollWrap = ref(null)
const observerElement = ref(null)

onMounted(() => {
  const options = {
    root: oScrollWrap.value, // null 使用浏览器的视口
    rootMargin: '0px', // 默认边界
    threshold: 0.5, // 当目标元素的 50% 可见时触发回调
  }

  const observer = new IntersectionObserver(callback, options)

  observer.observe(observerElement.value)

  //  取消监听
  onUnmounted(() => {
    observer.unobserve(observerElement.value)
  })
})
</script>

<style lang="scss" scoped>
/* 隐藏整个页面的滚动条 */
.scroll-wrap {
  overflow: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */

  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }

  .scroll-inner {
    width: 100%;
    height: 100%;
  }
}
</style>